//
//  ResetKeyController.m
//  华康通
//
//  Created by leiyu on 16/9/13.
//  Copyright © 2016年 com.huakang. All rights reserved.
//

#import "ResetKeyController.h"
#import "PhoneRegistController.h"
#import "UMMobClick/MobClick.h"

@interface ResetKeyController ()
@property (strong, nonatomic) IBOutlet UITextField *textField;
@property (strong, nonatomic) IBOutlet UILabel *coreLabel;
@property (strong, nonatomic) IBOutlet UIButton *nextButton;


@end



@implementation ResetKeyController


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
    [self.textField becomeFirstResponder];
    self.coreLabel.layer.cornerRadius = 6.0;
    self.coreLabel.layer.masksToBounds = YES;
}

- (void)popRootVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ResetKeyController"];//("PageOne"为页面名称，可自定义)
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [MobClick endLogPageView:@"ResetKeyController"];
}

//关闭键盘
- (IBAction)closeKeyboard:(UITextField *)sender
{
    [sender resignFirstResponder];
    [self nextVC:self.nextButton];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

//系统提示框
- (void)presentAlerControllerWithMessage:(NSString*)message withTextField:(UITextField*)textField
{
    NSLog(@"%@",message);
    [self.view endEditing:YES];
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    TextStatusView *customView  = [TextStatusView view];
    customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
    customView.bottomLabel.text = message;
    //    customView.layer.cornerRadius = 7.0;
    //    customView.layer.masksToBounds = YES;
    [alertView setContainerView:customView];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确认", @"取消", nil]];
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex)
        {
            case 0:
            [textField becomeFirstResponder];
            break;
            default:
            NSLog(@"取消操作" );
            break;
        }
    }];
    [alertView show];
}

//输入框文字改变的时候
- (IBAction)textChange:(UITextField *)sender
{
    if (![self.textField.text isEqualToString:@""])
    {
        self.coreLabel.backgroundColor = [UIColor colorWithPatternImage:LoadImage(@"login_btn.png")];
    }
    else
    {
        self.coreLabel.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:22.0/255.0 blue:0.0 alpha:0.1];
    }
}
//按下去 瞬间
- (IBAction)changeColor:(UIButton *)sender
{
    if (![self.textField.text isEqualToString:@""])
    {
        self.coreLabel.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:22.0/255.0 blue:0.0 alpha:1.0];
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC));
        dispatch_after(delay, dispatch_get_main_queue(), ^{
            
            self.coreLabel.backgroundColor = [UIColor colorWithPatternImage:LoadImage(@"login_btn.png")];
        });
    }
}


- (IBAction)changeLabelColor:(id)sender
{
    
}

#pragma mark  //判断用户名是否已经注册

- (void)showAlertViewWithMsg:(NSString*)msg
{
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    TextStatusView *customView  = [TextStatusView view];
    customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
    customView.bottomLabel.text = msg;
    //    customView.layer.cornerRadius = 7.0;
    //    customView.layer.masksToBounds = YES;
    [alertView setContainerView:customView];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确认", nil]];
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex)
        {
            case 0:
                [self.textField becomeFirstResponder];
                break;
            default:
                return ;
                break;
        }
    }];
    [alertView show];
}

- (void)postPrama
{
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"checkRegister",
                           @"requestObject":@{@"customerName":self.textField.text,
                                              }
                           };
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self getUserPhoneWithURL:url withParam:json];
}

- (void)getUserPhoneWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstance];
    [networking showErrorWithSuccess:^{
        
        [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"验证手机码是否已经注册json = %@",json);
            if ([json isKindOfClass:[NSDictionary class]] && json)
            {
                if ([json[@"resultCode"] isEqualToString:@"0"] && ![json[@"responseObject"][@"bindMobile"] isEqualToString:@""])
                {
                    
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                            PhoneRegistController* registVC=[storyboard instantiateViewControllerWithIdentifier:@"RegistVC"];
                            registVC.userPhone = json[@"responseObject"][@"bindMobile"];
                            registVC.title = @"重置密码";
                            registVC.myPushType = PushResetKeyVC;
                            [self.navigationController pushViewController:registVC animated:YES];
                        });
                        
                    });
                    
                    
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self showAlertViewWithMsg:@"您输入的工号或手机号码不存在,请重新输入!"];
                    });
                }
            }
        } failure:^(NSError *error) {
            NSLog(@"error.code = %@",error.userInfo);
            if (error.code == -1001)
            {
                NSLog(@"网络请求超时.....................");
            }
            
        }];
        
    } failure:^{
        //展示广告图
        NSLog(@"检测到设备无网络连接！！！");
    }];
    
    
}

//下一步
- (IBAction)nextVC:(UIButton *)sender
{
    [self.textField resignFirstResponder];
    if (![self.textField.text isEqualToString:@""] && self.textField.text)
    {
        //验证是否为工号或手机号码
        if ([ExamineTool verityPhoneWithString:self.textField.text] || [ExamineTool isUserCodeWithStr:self.textField.text])
        {
            NSLog(@"进入下一步...");
            [self postPrama];
        }
        else
        {
            __weak  ResetKeyController *wself = self;
//            [self presentAlerControllerWithMessage:@"您输入的工号/手机号码不合法！请重新输入" withTextField:self.textField];
            ShowAlertView(@"您输入的工号/手机号码不合法！请重新输入",wself.textField);
        }
    }
}


#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"textFieldDidBeginEditing");
}
//如果输入完
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
}


@end
